package top.lileix.example.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class AndroidClient {
	public static void main(String[] args) {
		AndroidClient a = new AndroidClient("172.16.8.36", 1017, new Notification() {

			@Override
			public void notif(String msg) {
				System.out.println(msg);

			}
		});
		a.run();
	}

	public String inetHost;
	public int inetPort;
	private Notification msg;

	public AndroidClient(String inetHost, int inetPort, Notification notification) {
		super();
		this.inetHost = inetHost;
		this.inetPort = inetPort;
		msg = notification;
	}

	public void run() {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch)
								throws Exception {
							ChannelPipeline pipeline = ch.pipeline();
							// 解码
							pipeline.addLast(
									"DelimiterBasedFrameDecoder",
									new DelimiterBasedFrameDecoder(
											8129,
											Delimiters.lineDelimiter()));
							// 解码
							pipeline.addLast("解码", new StringDecoder());
							// 编码
							pipeline.addLast("编码", new StringEncoder());
							pipeline.addLast(
									new ChatClientHandler(msg));
						}

					});
			ChannelFuture f = bootstrap.connect(inetHost, inetPort).sync();
			// Wait until the connection is closed.
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}

	public static interface Notification {
		public void notif(String msg);
	}
}
